// 分类映射
const categoryMap = {
    'frontend': '前端开发',
    'backend': '后端开发',
    'tools': '开发工具',
    'travel': '旅行日记',
    'food': '美食推荐'
};

// 获取URL参数中的分类
const getUrlCategory = () => {
    const params = new URLSearchParams(window.location.search);
    const category = params.get('category');
    return categoryMap[category] || category || '';
};

// 初始化编辑器
const initEditor = () => {
    const editor = new SimpleMDE({
        element: document.getElementById('content'),
        spellChecker: false,
        status: false,
        toolbar: [
            'bold', 'italic', 'heading', '|',
            'quote', 'unordered-list', 'ordered-list', '|',
            'link', 'image', '|',
            'preview', 'guide'
        ]
    });
    
    return editor;
};

// 初始化标签输入
const initTagInput = () => {
    const tagInput = document.getElementById('tag-input');
    const tagList = document.getElementById('tag-list');
    const tags = new Set();
    
    const addTag = (tag) => {
        if (tag && !tags.has(tag)) {
            tags.add(tag);
            const tagElement = document.createElement('span');
            tagElement.className = 'tag';
            tagElement.innerHTML = `
                ${tag}
                <button type="button" class="remove-tag">&times;</button>
            `;
            tagElement.querySelector('.remove-tag').addEventListener('click', () => {
                tags.delete(tag);
                tagElement.remove();
            });
            tagList.appendChild(tagElement);
        }
        tagInput.value = '';
    };
    
    tagInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter' || e.key === ',') {
            e.preventDefault();
            const tag = tagInput.value.trim();
            addTag(tag);
        }
    });
    
    tagInput.addEventListener('blur', () => {
        const tag = tagInput.value.trim();
        addTag(tag);
    });
    
    return () => Array.from(tags);
};

// 初始化图片上传
const initImageUpload = () => {
    const coverImage = document.getElementById('cover-image');
    const imagePreview = document.getElementById('image-preview');
    
    coverImage.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                imagePreview.src = e.target.result;
                imagePreview.style.display = 'block';
            };
            reader.readAsDataURL(file);
        }
    });
};

// 保存文章
const saveArticle = (editor, getTags) => {
    const title = document.getElementById('title').value.trim();
    const category = document.getElementById('category').value;
    const content = editor.value();
    const tags = getTags();
    const imagePreview = document.getElementById('image-preview');
    const coverImage = imagePreview.style.display !== 'none' ? imagePreview.src : '';
    
    if (!title) {
        alert('请输入文章标题');
        return;
    }
    
    if (!content) {
        alert('请输入文章内容');
        return;
    }
    
    const article = {
        id: Date.now(),
        title,
        category,
        content,
        tags,
        coverImage,
        date: new Date().toISOString()
    };
    
    // 从localStorage获取现有文章
    const articles = JSON.parse(localStorage.getItem('articles') || '[]');
    articles.push(article);
    localStorage.setItem('articles', JSON.stringify(articles));
    
    // 跳转到对应分类页面
    const categoryFiles = {
        '前端开发': 'frontend.html',
        '后端开发': 'backend.html',
        '开发工具': 'tools.html',
        '旅行日���': 'travel.html',
        '美食推荐': 'food.html'
    };
    
    window.location.href = categoryFiles[category] || 'index.html';
};

// 初始化预览
const initPreview = (editor) => {
    const updatePreview = () => {
        const title = document.getElementById('title').value || '文章标题';
        const content = editor.value() || '文章内容';
        const imagePreview = document.getElementById('image-preview');
        const coverImage = imagePreview.style.display !== 'none' ? imagePreview.src : '';
        
        const previewContent = document.getElementById('preview-content');
        previewContent.innerHTML = `
            <article class="article-card">
                ${coverImage ? `
                    <img src="${coverImage}" alt="${title}" class="article-image">
                ` : ''}
                <div class="article-content">
                    <h3 class="article-title">${title}</h3>
                    <div class="article-body">${marked.parse(content)}</div>
                </div>
            </article>
        `;
    };
    
    // 监听输入变化
    editor.codemirror.on('change', updatePreview);
    document.getElementById('title').addEventListener('input', updatePreview);
    
    // 初始预览
    updatePreview();
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    const editor = initEditor();
    const getTags = initTagInput();
    initImageUpload();
    initPreview(editor);
    
    // 设置默认分类
    const category = getUrlCategory();
    if (category) {
        document.getElementById('category').value = category;
    }
    
    // 发布按钮点击事件
    document.getElementById('publish-form').addEventListener('submit', (e) => {
        e.preventDefault();
        saveArticle(editor, getTags);
    });
}); 